package com.yh.consumer;

import com.rabbitmq.client.Channel;
import com.yh.dao.OrderDao;
import com.yh.entity.Orderinfo;
import com.yh.service.OrderService;
import com.yh.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 延迟队列专属消费者
 *
 * @Author yuhuan
 * @Date 2022/3/9
 */
@Component
public class DelayModuleConsumerBase extends BaseMqConsumer {
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(DelayModuleConsumerBase.class);

    @DubboReference(check = false)
    private OrderService orderService;
    @Autowired
    private OrderDao orderDao;

    /**
     * 检查订单是否已经支付，如果仍未支付则删除订单并释放被占用的座位
     */
    @RabbitListener(queues = Constants.RabbitMqData.DELAY_QUEUE_NAME, ackMode = "MANUAL")
    public void receiveOrderCheckMessage(String orderId, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        logger.debug(">>>>> 准备检查订单ID是否过期");
        // 获取订单信息
        Orderinfo orderByOrderId = orderDao.findOrderByOrderId(orderId);
        if (!ObjectUtils.isEmpty(orderByOrderId)) {
            // 检查订单
            int releaseSeatNum = orderService.orderCheck(orderByOrderId);
            if (releaseSeatNum > 0) {
                logger.debug(">>>>> 检查完毕，共释放座位数量" + releaseSeatNum + "个");
            }else {
                logger.debug(">>>>> 该订单已经完成支付");
            }
        }else {
            logger.debug(">>>>> 检查到不存在的订单信息，可能已经被标记为删除！");
        }
        // 消息确认
        messageConfirmation(channel, deliveryTag);
    }
}
